<script setup lang="ts">
import { ref, onMounted } from 'vue';
import TreeComponents, { type Callback } from '@/components/TreeComponents.vue';
import { type Tree } from '@/entity/FrontendStruct';
import { BIconFolderPlus, BIconFolderMinus, BIconPencilSquare } from 'bootstrap-icons-vue';
import converPage from '@/components/CoverPage.vue'
import { orgApi, formFormat } from '@/api/Api';
import type Node from 'element-plus/es/components/tree/src/model/node';
import { type Result } from '@/entity/BackendStruct';

interface AddForm {
  node: Tree
  name?: string
  show?: boolean
}
const emit = defineEmits(["item"])
const rootOrg: Tree = { id: -2, label: "根分组" }
const undefineOrg: Tree = { id: -1, label: "未分组" }
const opertaion = ref<string>('')
const data = ref<Tree[]>([])
const formData = ref<AddForm>({ node: rootOrg })
const editTreeData = ref()
// 主树回调
let callback: Callback = {
  // 当点击分组时发出点击事件
  click: (node: Tree, el: any, treeNode: any, evnet: any) => {
    emit("item", node);
  }
}

// 选择添加分组回调
let selectTreeCallback: Callback = {
  click(node, el, treeNode, evnet) {
    formData.value.node = node
    formData.value.show = false
  },
}

// 编辑回调
let eidtTreeCallback: Callback = {
  click(node, el, treeNode, evnet) {
    formData.value.node = node;
    formData.value.show = false;
    if (node.id > 0) {
      const input = document.createElement("input");
      input.setAttribute("autofocus", "");
      const contextValue = treeNode.refs.node$.children[0].children[1];
      const old = contextValue.textContent;
      contextValue.innerHTML = '';
      contextValue.appendChild(input);
      input.value = old;
      input.style.outline = '1px solid #4CAF50';

      input.onkeydown = (e: KeyboardEvent) => {
        if (e.code == 'Escape') {
          e.preventDefault();
          e.stopPropagation();
          contextValue.innerHTML = old;
        } else if (e.code == 'Enter') {
          if (input.value == '' || input.value == null) {
            contextValue.innerHTML = old;
          } else {
            formData.value.node.label = input.value;
            orgApi.orgChangeName({
              body: formFormat(formData.value.node),
              success: (result: Result) => {
                contextValue.innerHTML = input.value;
              },
              fail: (err: any) => {
                alert(err);
              }
            })
          }
        }
      }
      input.onmouseleave = () => {
        contextValue.innerHTML = old;
      }
      input.onclick = (e: Event) => {
        e.preventDefault();
        e.stopPropagation();
      }
      input.focus();
    }
  },
}
function treeMove(node: Node, target: Node, inner: any, event: any) {
  console.log(inner)
  if (inner == "inner") {
      orgApi.orgMove({body: formFormat({'id': node.data.id, 'pid': target.data.id}), success: (result: Result)=>{
      console.log(result);
      getOrg()
    }, fail: (err: any)=>{
      console.log(err)
    }});
  }

}

// 新增删除操作
const submitOrgOperation = () => {
  switch (opertaion.value) {
    case 'add':
      {
        if (formData.value.name == null || formData.value.name == '') {
          alert("分组名不能为空");
          return;
        }
        orgApi.orgAdd({
          body: formFormat({
            parent: formData.value.node.id,
            name: formData.value.name
          }),
          success: (result: Result) => {
            debugger
            if (result.code == 200) {
              getOrg();
            } else {
              alert(result.msg);
            }
            opertaion.value = ''
          },
          fail: (err: any) => {
            alert(err);
          }
        })
        break;
      }
    case 'delete':
      {
        orgApi.orgDel({
          body: formFormat({"id": formData.value.node.id}),
          success: (data: Result) => {
            if (data.code == 200) {
              getOrg();
            } else {
              alert(data.msg);
            }
            opertaion.value = '';
          },
          fail: (err: any) => {
            alert('其他错误');
            console.log(err);
            opertaion.value = '';
          },
        });
        break;
      }
  }
}

// 获取分组
const getOrg = () => {
  orgApi.getOrg({
    success: (resultData: Tree[]) => {
      data.value = [...resultData]
    }, fail: (err: any) => {
      console.log(err)
    }
  });
}

// 修改操作类型
const changeOperation = (type: string) => {
  formData.value.node = rootOrg;
  opertaion.value = type;
  if(type == 'edit'){
    editTreeData.value=[{...rootOrg, children: [...data.value]}]
  }
}


onMounted(() => {
  getOrg();
})
defineExpose({
  getOrgData: (callback: (_data: Tree[]) => {}, error: () => {}, flush: false) => {
    if (flush) {
      if (data.value != null)
        callback(data.value);
    } else {
      orgApi.getOrg({
        success: (resultData: Tree[]) => {
          data.value = [...resultData];
          callback(data.value);
        }, fail: (err: any) => {
          console.log(err)
        }
      });
    }
  }
})
</script>

<template>
  <div style="height: 35px;margin-top: 2px; margin-left: 25px">
    <el-button title="添加分组" @click="changeOperation('add')">
      <BIconFolderPlus></BIconFolderPlus>
    </el-button>
    <el-button title="删除分组" @click="changeOperation('delete')">
      <BIconFolderMinus></BIconFolderMinus>
    </el-button>
    <el-button title="编辑分组" @click="changeOperation('edit')">
      <BIconPencilSquare></BIconPencilSquare>
    </el-button>
  </div>

  <TreeComponents :data="data == null ? [undefineOrg] : [...data, undefineOrg]" :callback="callback" id="orgTree" />

  <converPage 
    style="max-width: 500px; min-width: 350px;"
    :title="(<any>({ add: '添加分组', delete: '删除分组', edit: '编辑分组' }))[opertaion]"
    :lefe-button="(<any>({ add: '添加', delete: '删除', edit: '' }))[opertaion]"
    :right-button="opertaion == ''  || opertaion == 'edit' ? '' : '取消'" 
    :show="opertaion != ''"
    @on-close="opertaion = ''"
    @click="formData.show = false" 
    @on-complate="submitOrgOperation"
    id='converPage'
  >

    <el-form v-if="opertaion == 'add'" :model="formData" label-width="auto" class="el-form-style">
      <el-form-item label="选定分组" style="margin-bottom: 5px;" @click.stop="">
        <el-input v-model="formData.name" :value="formData.node?.label"
          @click="formData.show = (formData.show == true ? false : true)" />
        <TreeComponents v-if="formData.show" :data="[rootOrg, ...data]" :defaultKeys="[-2]"
          :callback="selectTreeCallback" id="selectTree" />
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="formData.name" />
      </el-form-item>
    </el-form>

    <el-form v-if="opertaion == 'delete'" :model="formData" label-width="auto" class="el-form-style" @click.stop="">
      <el-form-item>
        <el-input v-model="formData.name" :value="(formData.node?.id < 0) ? '' : formData.node?.label"
          @click="formData.show = (formData.show == true ? false : true)" />
        <TreeComponents v-if="formData.show" :data="data" :callback="selectTreeCallback" id="selectTree" />
      </el-form-item>
    </el-form>
    <TreeComponents v-if="opertaion == 'edit'" :draggable="true" :move-position="['inner']" @move-end="treeMove"
      :data="editTreeData" :callback="eidtTreeCallback" />
  </converPage>

</template>

<style scoped>
#selectTree {
  position: absolute;
  top: 25px;
  left: 2px;
  z-index: 1;
  background-color: white;
  padding: 8px 20px 8px 1px;
  border: 1px;
  border: 1px solid var(--el-border-color);
  width: 85%
}

.el-form-style {
  max-width: 300px;
  width: 100%
}
</style>